<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="200">

            <u-form-item label="关联登录账户" prop="userId" required>
                <u-input v-model="validateForm.value.username" type="select" placeholder="请选择关联登录账号" right-icon="arrow-right"
                         @click="navigateTo(`/pages/common/sys-user-select/index`, null, validateForm.value)"/>
            </u-form-item>

            <u-form-item label="客户类型" prop="communityUserTypeId" required
                         v-if="validateForm.value.type === '1' && ('2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) !== -1)">

                <u-input type="select" :select-open="validateForm.controls.communityUserTypeId.isShow"
                         v-model="validateForm.controls.communityUserTypeId.textDesc"
                         placeholder="请选择客户类型" @click="validateForm.controls.communityUserTypeId.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>

            <u-form-item label="编号" prop="code" required>
                <u-input v-model="validateForm.value.code" placeholder="请输入编号"/>
            </u-form-item>

            <u-form-item label="名称" prop="name" required>
                <u-input v-model="validateForm.value.name" placeholder="请输入名称"/>
            </u-form-item>

            <u-form-item label="唯一身份标识" prop="idCard">
                <u-input v-model="validateForm.value.idCard" placeholder="请输入唯一身份标识"/>
            </u-form-item>

            <u-form-item label="联系人" prop="contact">
                <u-input v-model="validateForm.value.contact" placeholder="请输入联系人"/>
            </u-form-item>

            <u-form-item label="联系电话" prop="phone">
                <u-input v-model="validateForm.value.phone" placeholder="请输入联系电话"/>
            </u-form-item>

            <u-form-item label="联系地址" prop="address">
                <u-input type="textarea" height="40" placeholder="请输入联系地址" v-model="validateForm.value.address"/>
            </u-form-item>

            <u-form-item label="付款方式" prop="payType" required
                         v-if="'1,2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) !== -1">
                <u-input type="select" :select-open="validateForm.controls.payType.isShow"
                         v-model="validateForm.controls.payType.textDesc"
                         placeholder="请选择付款方式" @click="validateForm.controls.payType.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>

            <u-form-item label="指定负责人" prop="communityUserIds" v-if="validateForm.value.type === '1'">
                <u-input v-model="validateForm.value.communityUserNames" type="select" placeholder="请选择指定负责人（可选）" right-icon="arrow-right"
                         @click="navigateTo(`/pages/common/community-user-select/index`, null, validateForm.value)"/>
            </u-form-item>

            <u-form-item label="状态" prop="status" required>
                <u-input type="select" :select-open="validateForm.controls.status.isShow" v-model="validateForm.controls.status.textDesc"
                         placeholder="请选择状态" @click="validateForm.controls.status.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>

            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>

            <u-form-item label="备注" prop="remark">
                <u-input type="textarea" height="40" placeholder="请输入备注" v-model="validateForm.value.remark"/>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.communityUserTypeId.isShow"
                  v-model="validateForm.controls.communityUserTypeId.isShow" :list="validateForm.controls.communityUserTypeId.options"
                  :default-value="validateForm.controls.communityUserTypeId.defaultValue"
                  @cancel="validateForm.controls.communityUserTypeId.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.communityUserTypeId)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.payType.isShow"
                  v-model="validateForm.controls.payType.isShow" :list="validateForm.controls.payType.options"
                  :default-value="validateForm.controls.payType.defaultValue"
                  @cancel="validateForm.controls.payType.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.payType)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.status.isShow"
                  v-model="validateForm.controls.status.isShow" :list="validateForm.controls.status.options"
                  :default-value="validateForm.controls.status.defaultValue"
                  @cancel="validateForm.controls.status.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.status)"></u-select>

    </view>
</template>

<script>
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {CommonService} from "@/dev/services/common.service";
    import {SysDictionaryService} from "@/dev/services/sys-dictionary.service";
    import {TbCommunityUserTypeService} from "@/dev/services/tb-community-user-type.service";
    import {TbCommunityUserService} from "@/dev/services/tb-community-user.service";

    export default {
        data() {
            return {
                fileList: [],
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        communityId: this.globalVariable.userInfo.tbCommunity.id,
                        userId: '',
                        username: '',
                        communityUserTypeId: '',
                        code: '',
                        name: '',
                        idCard: '',
                        contact: '',
                        phone: '',
                        address: '',
                        payType: '0',
                        type: '',
                        status: '1',
                        displayOrder: '',
                        remark: '',
                        communityUserIds: '',
                        communityUserNames: '',
                        roleCodes: 'ROLE_STORE'
                    },
                    rules: {
                        userId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbCommunityUserService().isCanAssociation({
                                        communityId: this.validateForm.value.communityId,
                                        userId: value
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error(result.message));
                                        } else {
                                            callback()
                                        }
                                    });
                                }
                            }
                        ],
                        communityUserTypeId: [
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (this.validateForm.value.type === '1') {
                                        if (!value) {
                                            callback(new Error('必填项！'))
                                        } else {
                                            callback()
                                        }
                                    } else {
                                        callback()
                                    }
                                }
                            }
                        ],
                        code: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        "tableName": "tb_community_user_type",
                                        "fieldList": [
                                            {"fieldName": "community_id", "fieldValue": this.validateForm.value.communityId},
                                            {"fieldName": "code", "fieldValue": value},
                                        ],
                                        "excludeId": null
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('输入的内容已存在！'))
                                        } else {
                                            callback()
                                        }
                                    })
                                }
                            }
                        ],
                        payType: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        type: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        status: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        roleCodes: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;
            if (_self.urlParams.type === "0") {
                // 设置首页标题
                uni.setNavigationBarTitle({
                    title: '添加业务员'
                });
            } else if (_self.urlParams.type === "1") {
                // 设置首页标题
                uni.setNavigationBarTitle({
                    title: '添加客户'
                });
            }
            _self.validateForm.value.type = _self.urlParams.type;

            // 类型：0-业务员，1-客户
            if (_self.urlParams.type === '1') {
                new TbCommunityUserTypeService().findTbCommunityUserTypeList({
                    communityId: _self.globalVariable.userInfo.tbCommunity.id,
                    status: "1"
                }).then(result => {
                    UFormUtil.setOptions(_self.validateForm.controls.communityUserTypeId, [...CommonUtil.objectAlias(result, {'id': 'code'})]);
                    _self.$forceUpdate();
                });
            }

            new SysDictionaryService().optionList('tb_community_user@pay_type', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.payType, result);
                _self.$forceUpdate();
            });

            new SysDictionaryService().optionList('status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.status, result);
                _self.$forceUpdate();
            });
        },
        methods: {
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbCommunityUserService().saveTbCommunityUser(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功');
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
